package com.tongfusoft.web.core.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletOutputStream;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.tongfusoft.utils.DateUtils;
import com.tongfusoft.utils.UIDGeneratorService;
import com.tongfusoft.utils.excel.ExcelUtils;
import com.tongfusoft.web.core.data.Page;
import com.tongfusoft.web.core.data.TLogs;
import com.tongfusoft.web.core.data.User;
import com.tongfusoft.web.core.service.IDictionaryService;
import com.tongfusoft.web.core.service.IListService;
import com.tongfusoft.web.core.service.impl.ListServiceAdapter;

@SuppressWarnings("unchecked")
public class JsonListBaseAction extends BaseAction {
	private static final long serialVersionUID = 1L;

	private IListService listService;
	private IDictionaryService dictionaryService;

	protected String id;
	
	public IDictionaryService getDictionaryService() {
		return dictionaryService;
	}

	public void setDictionaryService(IDictionaryService dictionaryService) {
		this.dictionaryService = dictionaryService;
	}

	/**
	 * 分页类
	 */
	protected Page page = new Page();

	protected TLogs getLog(User user){
		TLogs tLog = new TLogs();
		tLog.setLogId(UIDGeneratorService.getUUID());
		tLog.setCreatedBy(user.getPkValue());
		tLog.setOperName(user.getUserDisplayName());
		tLog.setOperType("export");
		tLog.setMethodName(this.getClass().getName()+".export");
		
		String gridKey = (String)super.getParamByName("gridKey");
		if(ListServiceAdapter.LISTRB.getListElement(gridKey) != null){
			tLog.setLogContent("导出列表:" + ListServiceAdapter.LISTRB.getListElement(gridKey).getListName());
		}
		
		tLog.setOperResult("1"); //成功
		tLog.setParamsContent("");
		
		return tLog;
	}
	
	/**
	 * 导出Excel
	 */
	public void export() {
		ServletOutputStream out;
		try {
			super.getResponse().setContentType(
					"application/unknown;charset=utf-8");
			super.getResponse().setHeader("Content-Disposition",
					"attachment;filename=export.xls");

			out = super.getResponse().getOutputStream();

			HSSFWorkbook wb;
			wb = new HSSFWorkbook();
			HSSFSheet s = wb.createSheet();
			wb.setSheetName(0, "export");

			List<ExportDefine> titles = this.getListService().getExportTitle(getRequesAndSessiontMap());
			if (titles != null) {
				int index = 0;
				for (int i = 0; i < titles.size(); i++) {
					// 写表头
					ExportDefine map = titles.get(i);
					if(map.getExport()){
						ExcelUtils.setContent(s, 0, index, HSSFCell.CELL_TYPE_STRING,
								map.getTitle());
						index++;
					}
				}

				// 写数据
				s = writeData(titles, this.getAllData(), s);
			}

			wb.write(out);
			out.flush();

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			TLogs log = this.getLog(getCurrUser());
			this.getLogService().log(log);
		}

	}

	protected HSSFSheet writeData(List<ExportDefine> titles,
			List<Map<String, Object>> records, HSSFSheet s) {
		Map<String, Map<String, String>> dicts = this.getDict(titles);

		int indexRow = 1;
		for (Map<String, Object> map : records) { // 遍历数据
			int indexColumn = 0;
			for (ExportDefine title : titles) {
				//非导出字段不填写
				if(title.getExport()){
					if (StringUtils.isNotEmpty(title.getDictionaryCode())) {
						ExcelUtils.setContent(
								s,
								indexRow,
								indexColumn,
								HSSFCell.CELL_TYPE_STRING,
								dicts.get(title.getDictionaryCode()).get(
										(String) map.get(title.getKey())));
					} else {
						if (map.get(title.getKey()) instanceof String) {
							ExcelUtils.setContent(s, indexRow, indexColumn,
									HSSFCell.CELL_TYPE_STRING,
									(String) map.get(title.getKey()));
						} else if (map.get(title.getKey()) instanceof Number) {
							ExcelUtils.setContent(s, indexRow, indexColumn,
									HSSFCell.CELL_TYPE_STRING,
									((Number) map.get(title.getKey())).toString());
						} else if (map.get(title.getKey()) instanceof Date) {
							ExcelUtils.setContent(s, indexRow, indexColumn,
									HSSFCell.CELL_TYPE_STRING, DateUtils
											.formatDate(((Date) map.get(title
													.getKey()))));
						}
					}
					indexColumn++;
				}
				
			}
			indexRow++;
		}

		return s;
	}

	/**
	 * 获取所有数据
	 * 
	 * @return
	 */
	protected List<Map<String, Object>> getAllData() {
		// 分页取所有数据，每页3000笔
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		Map param = getRequesAndSessiontMap();
		
		this.getPage().setTotalCount(listService.getTotalCount(param));
		this.getPage().setPageSize(3000);

		for (int i = 1; i <= this.getPage().getTotalPages(); i++) { // 分页
			this.getPage().setPageNo(i);
			page = listService.findOnPage(param, page);
			if (page.getResult() != null && page.getResult().size() > 0) {
				result.addAll((List<Map<String, Object>>) page.getResult());
			}
		}

		return result;
	}

	/**
	 * 返回需要的所有字典参数
	 * 
	 * @param titles
	 * @return
	 */
	private Map<String, Map<String, String>> getDict(List<ExportDefine> titles) {
		Map<String, Map<String, String>> dicts = new HashMap<String, Map<String, String>>();

		Iterator<Entry<String,Object>> iter = super.getRequestParameters().entrySet().iterator();
		while(iter.hasNext()){
			Entry<String,Object> entry = iter.next();
			if(StringUtils.startsWith("dict_",entry.getKey())){
				for(ExportDefine title : titles){
					if(StringUtils.equals(title.getKey(),entry.getKey().substring(4))){
						title.setDictionaryCode((String)entry.getValue());
						dicts.put((String)entry.getValue(),this.getDictionaryService().getDictByCode((String)entry.getValue()));
					}
				}
			}
				
		}
		
		return dicts;
			
			
	/*		for (ExportDefine title : titles) {
				if (StringUtils.isNotEmpty(title.getDictionaryCode())) {
					// List<Map> optionList =
					// this.getDictService().getOptions(title.getDictionaryCode());
					// TODO 获取字典
					List<Map> optionList = new ArrayList<Map>();
					Map<String, String> options = new HashMap<String, String>();
					for (Map option : optionList) {
						options.put((String) option.get("ID"),
								(String) option.get("LABEL"));
					}
					dicts.put(title.getDictionaryCode(), options);
				}
			}
		}

		return dicts;*/
	}
	

	/**
	 * 获取列表
	 * @return
	 */
	public String list() {
		try {
			Map param = getRequesAndSessiontMap();

			this.getPage().setTotalCount(listService.getTotalCount(param));
			page = listService.findOnPage(param, page);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}

		return "list";
	}

	public JsonListBaseAction() {
		super();
	}

	public Page getPage() {
		return page;
	}

	public void setPage(Page page) {
		this.page = page;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getId() {
		return id;
	}

	public IListService getListService() {
		return listService;
	}

	public void setListService(IListService listService) {
		this.listService = listService;
	}

}
